package  com.wkkun.particle.circle

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import com.wkkun.particle.base.BaseItem
import kotlin.math.cos
import kotlin.math.sin
import kotlin.random.Random

/**
 *Date:2020/4/10
 *Author:wang kunkun
 *Des:
 **/
class CircleItem(private val parentWidth: Int, private val parentHeight: Int,
                 private var baseRadius: Float = 100f) :
    BaseItem {
    companion object {
        const val STATE_LIVE = 1
        const val STATE_DIE = 0
    }

    private var state = STATE_DIE
    //发散的角度 从0到360
    private var angle = 0
    //当前的位置
    private var currentX = 0f
    private var currentY = 0f
    //半径
    private var radius = 0
    //速度
    private var speed = 4
    private var currentRadius = 0f
    private var finalRadius = 0f
    //透明的距离
    private var alphaDis = 0f
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)

    init {
        paint.color = Color.parseColor("#ff18bdc7")
    }


    override fun init(context: Context) {
        angle = Random.nextInt(0, 360)
        currentRadius = baseRadius
        finalRadius = Random.nextInt(parentWidth / 3, parentWidth / 2).toFloat()
        radius = Random.nextInt(6, 13)
        alphaDis = finalRadius * 0.1f
        paint.alpha = 255
        calculateXY()
    }

    override fun preInit(context: Context) {
        init(context)
    }

    private fun calculateXY() {
        currentX = (currentRadius * sin(angle.toDouble()) + parentWidth / 2).toFloat()
        currentY = (currentRadius * cos(angle.toDouble()) + parentHeight / 2).toFloat()
        //透明度 设置 最后10% 从不透明到透明
        val dis = finalRadius - currentRadius
        if (dis <= alphaDis) {
            paint.alpha = (dis / alphaDis * 255 + 0.5).toInt()
        }
    }

    override fun move(): Boolean {
        currentRadius += speed
        if (currentRadius > finalRadius) {
            return false
        }
        calculateXY()
        return true
    }

    override fun reset() {
    }

    override fun draw(canvas: Canvas) {
        canvas.drawCircle(currentX, currentY, radius.toFloat(), paint)
    }

    override fun isLive(): Boolean {
        return state == STATE_LIVE
    }

    override fun destroy() {
    }
}